package design_pattern.ThreadPerMessage;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/18 9:01
 * @Version 1.0
 */
public class MessageHandler {
    private final Random random = new Random(System.currentTimeMillis());
    private final static Executor executor = Executors.newFixedThreadPool(5);

    public void request(Message message){
        executor.execute(()->{
            String value = message.getValue();
            System.out.println("The message will be handle by"+Thread.currentThread().getName()+" "+value);
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    public void shutdown(){
        ((ExecutorService)executor).shutdown();
    }
}